/*
 * @Author: CodeHare
 * @Date: 2023-11-20 14:19:16
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-26 17:13:11
 * @Description: 报障单列表
 */
import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/pages/tasks/my_fault_report/fault_report_list_state.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/task/task_services.dart';
import 'package:yt_devops/utils/enums.dart';

class FaultReportListController extends GetxController {
  final TaskServices services = Get.put(TaskServices());
  final FaultReportListState state = FaultReportListState();

  /// 检索
  late List<int> siteIds;
  FocusNode searchSiteFocusNode = FocusNode();
  TextEditingController textController = TextEditingController();
  BrnSearchTextController searchController = BrnSearchTextController();

  /// 多条件检索
  /// 已选中的站点列表
  List<SiteTagModel> selectedSites = [];

  List<ReportTaskStatusType> selectTags = [];
  String startTime = '';
  String endTime = '';

  /// 请求参数
  FaultReportListReqParams reqParams = FaultReportListReqParams();

  @override
  void onInit() {
    loadData(isloading: true);
    super.onInit();
  }

  Future loadMoreData() async {
    state.pageNum++;
    await loadData(isloading: false);
  }

  Map<String, dynamic> _collectParams() {
    reqParams.current = state.pageNum;
    reqParams.pageSize = state.pageSize;

    /// 工单号
    reqParams.id = state.id;
    reqParams.startTime = state.startTime;
    reqParams.endTime = state.endTime;
    reqParams.siteIds = selectedSites.map((e) => e.siteId).toList();
    ;
    reqParams.status = state.status;

    return reqParams.toJson();
  }

  Future loadData({isloading = false}) async {
    try {
      var params = _collectParams();
      if (isloading) {
        showLoading(toast: ResKey.loading.tr);
      }

      var response = await services.getReportTaskList(params);
      if (state.pageNum == 1) state.dataList.clear();
      var list = response['list'] ?? [];
      list.forEach(
          (item) => state.dataList.add(FaultReportItemModel.fromJson(item)));

      state.hasMore = list.length < 10 ? false : true;
      if (state.pageNum == 1) {
        state.refreshController.refreshCompleted();
      } else {
        state.refreshController.loadComplete();
      }
      update();

      dismissLoading();
    } catch (e) {
      dismissLoading();
      handleException(ApiException.from(e));
      if (state.pageNum == 1) {
        state.refreshController.refreshFailed();
      } else {
        state.refreshController.loadFailed();
      }
    }
  }

  void addNewFaultReportTask() {
    Get.toNamed(RouterPath.createFaultReport)!.then((value) => {
          if (value == true) {loadData(isloading: false)}
        });
  }

  /// 获取搜索列表站点名称
  void getSearchFaultReportName(String? name) {
    if (name == null || name.isEmpty) {
      state.id = null;
    } else {
      state.id = int.parse(name);
    }

    loadData(isloading: true);
  }

  /// 进入报障任务详情
  void toDetails(int id, ReportTaskStatusType status) {
    Get.toNamed(RouterPath.faultReportDetail, arguments: {
      'id': id,
      'status': status,
    })?.then((value) {
      if (value == true) {
        loadData();
      }
    });
  }

  Future refreshData({isLoading = false}) async {
    state.pageNum = 1;
    await loadData(isloading: isLoading);
  }

  @override
  void onClose() {
    searchSiteFocusNode.dispose();
  }
}
